#!/usr/bin/env python
#coding:utf-8
#####################
#ticket.py 一个火车票的刷新程序。
#说实在的，这个程序后面写得一点都不简洁。
#看来调试成功后，需要进行重构。
#####################

import urllib2
import mailbox
import time
import os
import re
import sys
import string
from sgmllib import SGMLParser

class URLLister(SGMLParser):
    is_a = ""
    name = []

    def start_a(self, attrs):
        self.is_a = 1

    def end_a(self):
        self.is_a = ""

    def handle_data(self, text):
        if self.is_a:
            self.name.append(text)

print "Usage:" + sys.argv[0] + " train date"
urls = ["http://piao.kuxun.cn/","http://www.58.com/huochepiao/"]

train = sys.argv[1]
date = sys.argv[2]
From = sys.argv[3]
To = sys.argv[4]

stop = 5

cache = []

while 1:
    try:
        for url in urls:
            request = urllib2.Request(url+From+"-"+To)
            request.add_header("User-Agent","Mozilla/5.0")
            opener = urllib2.build_opener()
            data = opener.open(request).read()
            ticket_name = URLLister()
            ticket_name.feed(data)

            if url.find("kuxun") >= 0:
                web = "kuxun.cn"
                Date = date.split(".")
                if string.atoi(Date[1])<10:
                    Time = Date[0] + '-' + Date[1]
            else:
                web = '58.com'
                Date = date.split('.')
                if string.atoi(Date[1])<10:
                    Time = Date[0] + '-0' + Date[1]

            ticket = "no"
            cache = []
            for result in ticket_name.name:
                if result and result.find(Time) >= 0 and result.find(train)>=0:
                    if result in cache:
                        pass
                    else:
                        ticket = "yes"
                        print "Found in "+web+": "+train+" on 2010-"+Time+" from"+From+"to"+To
            if ticket == "no":
                print "No ticket in " + web + ": " + train +" on 2010-" + Time + " from " + From + " to " + To

            cache = []
            opener.close()
            time.sleep(stop)
    except:
        raise
